package com.cenntro.common.base;

import java.beans.PropertyEditorSupport;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.cenntro.common.exception.BizException;
import com.cenntro.common.util.MessageUtil;
import com.cenntro.common.util.result.Result;

@ControllerAdvice
public class BaseController {

	private static final Logger LOG = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	private MessageSource messageSource;

	/**
	 * 统一异常处理
	 * 
	 * @param exception
	 *            exception
	 * @return
	 */
	@ExceptionHandler({ Throwable.class })
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Object processException(Throwable exception) {
		LOG.error("系统异常：", exception);
		if (exception instanceof IllegalArgumentException) {
			return Result.error(MessageUtil.PARAM_ILLEGAL, exception.getMessage());
		} else if (exception instanceof BizException) {
			BizException biz = (BizException) exception;
			return Result.error(biz.getErrorCode(), biz.getMessage());
		} else if (exception instanceof org.springframework.validation.BindException) {
			BindException ex = (BindException) exception;
			StringBuilder err = new StringBuilder();
			for (ObjectError errer : ex.getBindingResult().getAllErrors()) {
				String errMsg = null;
				errMsg = MessageUtil.getMsg(errer.getDefaultMessage(), errer.getArguments());
				err.append(errMsg).append(",");
			}
			return Result.error(MessageUtil.ERROR, err.toString());
		} else if (exception instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException e = (MethodArgumentNotValidException) exception;
			StringBuilder err = new StringBuilder();
			for (ObjectError errer : e.getBindingResult().getAllErrors()) {
				err.append(errer.getDefaultMessage()).append(",");
			}
			return Result.error(MessageUtil.ERROR, err.toString());
		} else if(exception instanceof SQLException){
			return Result.error(MessageUtil.ERROR, "SQLException");
		}else if(exception instanceof AuthorizationException){
		    return Result.error(-9, "登录已经过期");
		}else{
			return Result.error(MessageUtil.ERROR, "出错了");
		}
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			public void setAsText(String value) {
				try {
					setValue(DateUtils.parseDate(value, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
				} catch (ParseException e) {
					setValue(null);
				}
			}

//			public String getAsText() {
//				return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
//			}
		});
		
//		Validator validator = Validation.byDefaultProvider()
//                .configure()
//                .messageInterpolator(new ResourceBundleMessageInterpolator(new PlatformResourceBundleLocator("i18n/messages_validate" )))
//                .buildValidatorFactory()
//                .getValidator();
//		validator.validate(object, groups);
	}

}
